package Utils;

import MyException.InvalidCookieException;
import MyException.VerificationCodeAppearsException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.ProtocolException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import javax.net.ssl.*;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpConnect {


    public static String HttpGet_OkHttp(String url, Map<String, String> header_map) throws IOException {
        OkHttpClient.Builder ok_builder = new OkHttpClient.Builder();
        ok_builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 4780)));


        OkHttpClient client = ok_builder
                .sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts())
                .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();
        Request.Builder builder = new Request.Builder();
        if (header_map != null) {
            for (Map.Entry<String, String> map : header_map.entrySet()) {
                builder.addHeader(map.getKey(), map.getValue());
            }
        }

        Request request = builder.url(url).get().build();

        int call_time = 0;
        while (call_time <= 10) {
            try {

                Response response = client.newCall(request).execute();
                String str = response.body().string();
                if (str.equals(""))
                    throw new IOException();
                return str;
            } catch (IOException e) {
                e.printStackTrace();
                call_time++;
            }
        }

        if (call_time > 10) {
            throw new IOException("html is empty! url = " + url);
        }
        return null;
    }

    public static String HttpPost_OkHttp(String url, Map<String, String> header_map, Map<String, String> data_map) throws ProtocolException {
        OkHttpClient.Builder ok_builder = new OkHttpClient.Builder();
        ok_builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 4780)));

        OkHttpClient client = ok_builder
                .sslSocketFactory(createSSLSocketFactory(), new TrustAllCerts())
                .hostnameVerifier(new TrustAllHostnameVerifier())
                .build();

        FormBody.Builder form_builder = new FormBody.Builder();
        for (Map.Entry<String, String> map : data_map.entrySet()) {
            form_builder.add(map.getKey(), map.getValue());
        }
        FormBody formBody = form_builder.build();

        Request.Builder builder = new Request.Builder();
        for (Map.Entry<String, String> map : header_map.entrySet()) {
            builder.addHeader(map.getKey(), map.getValue());
        }
        Request request = builder.url(url).post(formBody).build();


        int call_time = 0;
        while (call_time <= 10) {
            try {
                Response response = client.newCall(request).execute();
                String str = response.body().string();
                if (str.equals(""))
                    throw new IOException();
                return str;
            } catch (IOException e) {
                e.printStackTrace();
                call_time++;
            }
        }
        return null;
    }



    public static void checkHtml(String html, String url) throws InvalidCookieException, VerificationCodeAppearsException, IOException {
        /**
         * 检验页面
         */
        if (html.contains("对不起，服务器上不存在此用户！可能已经被剔除或参数错误")) {
            throw new InvalidCookieException("url = " + url);
        }

        if (html.contains("<label>验证码：</label>")) {
            throw new VerificationCodeAppearsException("url = " + url);
        }

        if (html.equals("")) {
            throw new IOException("html is empty! url = " + url);
        }
    }

    private static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }
}

